package com.flight.trans.fragment;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.flight.trans.R;
import com.flight.trans.activity.StoreroomInventoryDetailsActivity;
import com.flight.trans.adapter.StoreroomInventoryAdapter;
import com.flight.trans.bean.StoreroomInventoryBean.StoreroomInventoryData;
import com.flight.trans.global.Constant;
import com.flight.trans.global.ConstantInfo;
import com.flight.trans.http.NetworkUtils;
import com.flight.trans.http.network.OkGoBackListener;
import com.flight.trans.listener.OnItemClickListener;
import com.flight.trans.listener.OnSheetItemClickListener;
import com.flight.trans.util.ChinaToPinyin;
import com.flight.trans.util.CommonUtils;
import com.flight.trans.util.LogUtils;
import com.flight.trans.util.ProgressUtils;
import com.flight.trans.view.HeaderTitleView;
import com.flight.trans.base.BaseFragment;
import com.flight.trans.view.dialog.BottomDialog;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lzy.okgo.model.HttpParams;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 盘库
 */
public class StoreroomInventoryFragment extends BaseFragment {

    private HeaderTitleView mHeaderView ;

    private TextView mTvOrderCount ,//运单数
            mTvNotInventoryCount ,//未盘运单数
            mTvInventoryPerson ,//盘库人
            mTvInventoryTime ,//盘库时间
            mTvInventoryResult ;//盘库结果

    private TwinklingRefreshLayout mRefreshLayout ;
    private RecyclerView mRvContainer ;
    private RelativeLayout mRlContentNull ;

    private List<StoreroomInventoryData> mInventoryDataList ,mSearchDataList;
    private StoreroomInventoryAdapter mInventoryAdapter;

    private int turnType ;

    private int mSortState = -1;

    public StoreroomInventoryFragment(int turnType){
        this.turnType = turnType ;
    }

    @Override
    public int setContentView() {
        return R.layout.fragment_storeroom_inventory;
    }

    @Override
    public void initView() {
        mTvOrderCount = mView.findViewById(R.id.mTvOrderCount);
        mTvNotInventoryCount = mView.findViewById(R.id.mTvNotInventoryCount);
        mTvInventoryPerson = mView.findViewById(R.id.mTvInventoryPerson);
        mTvInventoryTime = mView.findViewById(R.id.mTvInventoryTime);
        mTvInventoryResult = mView.findViewById(R.id.mTvInventoryResult);

        mHeaderView = mView.findViewById(R.id.mHeaderView);
        mRefreshLayout = mView.findViewById(R.id.mRefreshLayout);
        mRvContainer = mView.findViewById(R.id.mRvContainer);
        mRlContentNull = mView.findViewById(R.id.mRlContentNull);
    }

    @Override
    public void initData() {
        mHeaderView.setTitleName(getString(turnType == 0 ? R.string.title_enter_port_inventory : R.string.title_leave_port_inventory));

        initHeaderView();

        mTvOrderCount.setOnClickListener(this::onClickSort);
        mTvNotInventoryCount.setOnClickListener(this::onClickSort);
        mTvInventoryPerson.setOnClickListener(this::onClickSort);
        mTvInventoryTime.setOnClickListener(this::onClickSort);
        mTvInventoryResult.setOnClickListener(this::onClickSort);

        setRefreshListener(mRefreshLayout);
    }

    @Override
    public void initConnect() {
        if(mHeaderView == null) return;

        valueParams = new HttpParams();
        valueParams.put(Constant.Key_Check_Date , mHeaderView.getSelectDate());

        NetworkUtils.getStoreroomInventoryList(new OkGoBackListener(mActivity) {
            @Override
            public void onSuccess(Object body) {
                mInventoryDataList = (List<StoreroomInventoryData>) body;

                onScanResult(mHeaderView.getSearchContent());
            }
        }, valueParams , turnType == 0);
    }

    private void initAdapter(){
        mRlContentNull.setVisibility(mInventoryDataList == null || mInventoryDataList.size() == 0 ? View.VISIBLE : View.GONE);
        mRefreshLayout.setVisibility(mInventoryDataList == null || mInventoryDataList.size() == 0 ? View.GONE : View.VISIBLE);

        if(mInventoryAdapter == null) {
            mInventoryAdapter = new StoreroomInventoryAdapter(mActivity, mInventoryDataList);
            mRvContainer.setAdapter(mInventoryAdapter);
            mRvContainer.setLayoutManager(new LinearLayoutManager(mActivity));

            mInventoryAdapter.setOnItemClickListener(onItemClickListener);
        }else {
            mInventoryAdapter.updateAdapter(mInventoryDataList);
        }
    }

    /**
     * 点击事件
     */
    private String[] dateTimes ,dates,times,nowDateTimes,nowDates,nowTimes;
    private BottomDialog mBottomDialog ;
    private OnItemClickListener onItemClickListener = new OnItemClickListener(){
        @Override
        public void onClick(View view, int position) {

            dateTimes = mInventoryDataList.get(position).getCreateTime().split(" ");
            dates = dateTimes[0].split("-");
            times = dateTimes[1].split(":");

            nowDateTimes = CommonUtils.getTime().split(" ");
            nowDates = nowDateTimes[0].split("-");
            nowTimes = nowDateTimes[1].split(":");

            boolean isRevise = false ;

            if(Integer.parseInt(dates[0]) == Integer.parseInt(nowDates[0]) && Integer.parseInt(dates[1]) == Integer.parseInt(nowDates[1])) {
                if (Integer.parseInt(dates[2]) == Integer.parseInt(nowDates[2])) {
                    isRevise = Integer.parseInt(times[0]) > ConstantInfo.StoreroomInventoryTime;
                } else if (Integer.parseInt(dates[2]) + 1 == Integer.parseInt(nowDates[2])) {
                    isRevise = Integer.parseInt(nowTimes[0]) < ConstantInfo.StoreroomInventoryTime;
                }
            }

            mBottomDialog = BottomDialog.getInstance(mActivity);
            if(isRevise)
                mBottomDialog.addSheetItem(R.string.text_continue_inventory);
            mBottomDialog.addSheetItem(R.string.text_check_result);
            mBottomDialog.setOnItemClickListener(new InventoryItemClickListener(position))
                    .show();
        }
    };

    /**
     * 条目点击事件
     */
    private class InventoryItemClickListener implements OnSheetItemClickListener {
        private int position ;
        public InventoryItemClickListener(int position){
            this.position = position;
        }
        @Override
        public void onClick(int which) {
            // 继续盘库、查看结果
            getPageLock(which == 0 , mInventoryDataList.get(position));
        }
    }

    /**
     * 跳转到详情页面
     * @param isEditor
     */
    private void getPageLock(boolean isEditor , StoreroomInventoryData inventoryData){
        NetworkUtils.checkPageLock(new OkGoBackListener(mActivity) {
            @Override
            public void onSuccess(Object body) {
                turnDetailsActivity(isEditor , inventoryData);
            }
        }, turnType == 0 ? ConstantInfo.IN_STORAGE_CHECK : ConstantInfo.OUT_STORAGE_CHECK , inventoryData.getId());
    }

    /**
     * 跳转到详情页面
     * @param isEditor
     */
    private void turnDetailsActivity(boolean isEditor , StoreroomInventoryData inventoryData){
        mIntent = new Intent(mActivity , StoreroomInventoryDetailsActivity.class);
        mBundle = new Bundle();
        mBundle.putInt(Constant.TurnType , turnType);
        mBundle.putBoolean(Constant.IsEditor , isEditor);
        mBundle.putSerializable(Constant.INFO , inventoryData);
        mIntent.putExtras(mBundle);
        turnActForResult(mIntent);
    }

    private void initHeaderView() {
        mHeaderView.addOnHeaderListener(new HeaderTitleView.OnHeaderListener(){
            @Override
            public void onClick(int resource) {
                switch (resource){
                    case R.id.mTvCommon:
                        turnDetailsActivity(true , null);
                        break;
                }
            }

            @Override
            public void onSearch(String search) {
                onScanResult(search);
            }

            @Override
            public void onDateChange(String date) {
                ProgressUtils.showProgress(mActivity);
                initConnect();
            }
        });
    }

    public void onClickSort(View view){
        mSortState = (mSortState != 0 && R.id.mTvOrderCount == view.getId()) ? 0 : (mSortState == 0 ? -1 : mSortState) ;
        mSortState = (mSortState != 1 && R.id.mTvNotInventoryCount == view.getId()) ? 1 : mSortState == 1 ? -1 : mSortState ;
        mSortState = (mSortState != 2 && R.id.mTvInventoryPerson == view.getId()) ? 2 : mSortState == 2 ? -1 : mSortState ;
        mSortState = (mSortState != 3 && R.id.mTvInventoryTime == view.getId()) ? 3 : mSortState == 3 ? -1 : mSortState ;

        mTvOrderCount.setTextColor(mActivity.getColor(mSortState == 0 ? R.color.color_red : R.color.color_blue));
        mTvNotInventoryCount.setTextColor(mActivity.getColor(mSortState == 1 ? R.color.color_red : R.color.color_blue));
        mTvInventoryPerson.setTextColor(mActivity.getColor(mSortState == 2 ? R.color.color_red : R.color.color_blue));
        mTvInventoryTime.setTextColor(mActivity.getColor(mSortState == 3 ? R.color.color_red : R.color.color_blue));

        onScanResult(mHeaderView.getSearchContent());
    }

    public void onScanResult(String search) {
        mSearchDataList = new ArrayList<>();

        if(!TextUtils.isEmpty(search)) {
            for (int i = 0; i < mInventoryDataList.size(); i++)
                if(mInventoryDataList.get(i).getUserName() != null && mInventoryDataList.get(i).getUserName().contains(search))
                    mSearchDataList.add(mInventoryDataList.get(i));
        }else {
            mSearchDataList.addAll(mInventoryDataList);
        }

        if(mSearchDataList != null)
            if(mSortState == 0){
                Collections.reverse(mSearchDataList);
            }else if(mSortState != -1){
                Collections.sort(mSearchDataList, new SortComparator(mSortState));
            }

        initAdapter();
    }

    /**
     * 排序集合
     */
    private class SortComparator implements Comparator<StoreroomInventoryData> {

        private int type;

        public SortComparator(int type){
            this.type = type;
        }

        @Override
        public int compare(StoreroomInventoryData data1, StoreroomInventoryData data2) {
            switch (type){
                case 0 :
                    return data2.getOrderCnt() - data1.getOrderCnt();
                case 1 :
                    return data2.getUndoneOrderCnt() - data1.getUndoneOrderCnt();
                case 2 :
                    return ChinaToPinyin.getInstance().sort(data1.getUserName() , data2.getUserName());
                case 3 :
                    // 盘库时间
                    return (int) (CommonUtils.getTimeLong(data2.getCreateTime()) - CommonUtils.getTimeLong(data1.getCreateTime()));
                default:
                    return 0 ;
            }
        }
    }
}
